import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/useStore'

const routes = [
  {
    path: '/:path(.*)+',
    name: 'NotFound',
    redirect: { name: 'ClientLanding' },
  },
  {
    path: '/error',
    name: 'ErrorPage',
    component: () => import('@/view/error/Error.vue'),
    meta: { title: '错误' },
  },
  {
    path: '/landing',
    name: 'ClientLanding',
    component: () => import('@/view/user/Login.vue'),
    meta: { title: '用户登录' },
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/view/user/Home.vue'),
    meta: { title: '用户主页', requiresAuth: true },
  },
  {
    path: '/admin/login',
    name: 'AdminLogin',
    component: () => import('@/view/admin/Login.vue'),
    meta: { title: '管理员登录' },
  },
  {
    path: '/admin/home',
    name: 'AdminHome',
    component: () => import('@/view/admin/AdminHome.vue'),
    meta: { title: '后台管理', requiresAuth: true, isAdmin: true },
  },
]

const router = createRouter({
  routes,
  history: createWebHashHistory(),
})

// **全局前置守卫**
router.beforeEach((to, from, next) => {
  const title = to.meta?.title
  if (title) {
    document.title = title as string
  }

  const userStore = useUserStore()
  const isAuthenticated = !!userStore.getAuthToken() // 判断是否已登录
  const isAdminRoute = to.meta.isAdmin // 判断是否是后台管理页面
  if (!isAdminRoute) {
    // **用户未登录，访问受限页面时跳转**
    if (to.meta.requiresAuth && !isAuthenticated) {
      return next('/landing') // 未登录跳转到用户登录页
    }

    // **已登录用户访问登录页面，直接跳转到首页**
    if (to.path === '/landing' && isAuthenticated) {
      return next('/home')
    }
  } else {
    // **普通用户不能访问后台管理页**
    if (!isAuthenticated) {
      return next('/admin/login') // 跳转到管理员登录页
    }

    // **已登录用户访问登录页面，直接跳转到首页**
    if (to.path === '/admin/login' && isAuthenticated) {
      return next('/admin/home')
    }
  }

  next() // 继续跳转
})

export default router
